package com.imooc.luckymoney.service;

import com.imooc.luckymoney.entity.Consumer;
import com.imooc.luckymoney.entity.Luckymoney;
import com.imooc.luckymoney.entity.Result;
import com.imooc.luckymoney.entity.LuckymoneyId;
import com.imooc.luckymoney.enums.ResultEnum;
import com.imooc.luckymoney.exception.LuckymoneyException;
import com.imooc.luckymoney.repository.LuckymoneyRepository;
import com.imooc.luckymoney.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Optional;

@Service
public class LuckymoneyService {

    @Autowired
    LuckymoneyRepository repository;

//    @Transactional
//    public void creatTwo(){
//        Luckymoney luckymoney1 = new Luckymoney();
//        luckymoney1.setProducer("hgw");
//        luckymoney1.setMoney(new BigDecimal("520"));
//        repository.save(luckymoney1);
//
//        Luckymoney luckymoney2 = new Luckymoney();
//        luckymoney2.setProducer("hgw");
//        luckymoney2.setMoney(new BigDecimal("1314"));
//        repository.save(luckymoney2);
//    }


    public String checkMoney(int id){
        Luckymoney luckymoney = repository.findById(id).orElse(null);
        if (luckymoney != null){
            BigDecimal money = luckymoney.getMoney();
            if(money.compareTo(new BigDecimal(100)) == 1){
                throw new LuckymoneyException(ResultEnum.SUCCESS);
            }else{
                throw new LuckymoneyException(ResultEnum.ID_EMPTY_ERROR);
            }
        }
        throw new LuckymoneyException(ResultEnum.FIND_BY_ID_ERROR);
    }

    public Result<Luckymoney> create(Luckymoney luckymoney){
        return ResultUtil.success(repository.save(luckymoney));
    }

    public Result<Luckymoney> findById(LuckymoneyId id){
        Optional<Luckymoney> optional = repository.findById(id.getId());
        if(optional.isPresent()){
            return ResultUtil.success(optional.get());
        }else {
            throw new LuckymoneyException(ResultEnum.FIND_BY_ID_ERROR);
        }
    }

    public Result deleteById(LuckymoneyId id){
        if(repository.findById(id.getId()).isPresent()){
            throw new LuckymoneyException(ResultEnum.SUCCESS);
        }else{
            throw new LuckymoneyException(ResultEnum.FIND_BY_ID_ERROR);
        }
    }
    public Result update(Consumer consumer) {
        Optional<Luckymoney> optional = repository.findById(consumer.getId());
        if(optional.isPresent()){
            Luckymoney luckymoney = optional.get();
            luckymoney.setConsumer(consumer.getConsumer());
            return ResultUtil.success(repository.save(luckymoney));
        }else {
            throw new LuckymoneyException(ResultEnum.FIND_BY_ID_ERROR);
        }
    }
}
